package com.cckp.zeroCopy;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;

/**
 * @author lijiasheng2  2021/10/29.
 */
public class ZeroCopy1 {
    public static void main(String[] args) throws Exception {
        File input = new File("D:\\tmp\\zerocopy_a\\Postman-win64-8.12.4-Setup.exe");
        File zcOutput = new File("D:\\tmp\\zerocopy_b\\Postman-win64-8.12.4-Setup.exe");
//        ZeroCopy(input, zcOutput);
        traditionalCopy(input,zcOutput);
    }

    public static void ZeroCopy(File input, File output) throws Exception {
        long start = System.currentTimeMillis();
        //文件输出
        FileInputStream fis = new FileInputStream(input);
        //源文件通道
        FileChannel srcFC = fis.getChannel();
        //输出流
        FileOutputStream fos = new FileOutputStream(output);
        //输出文件通道
        FileChannel destFC = fos.getChannel();
        srcFC.transferTo(0, input.length(), destFC);
        long end = System.currentTimeMillis();
        System.out.println("ZeroCopy 用时为:" + (end - start) + "ms");
    }

    public static void traditionalCopy(File input, File output) throws Exception {
        long start = System.currentTimeMillis();
        RandomAccessFile rafRead = new RandomAccessFile(input, "rw");
        RandomAccessFile rafWrite = new RandomAccessFile(output, "rw");
        byte[] buf = new byte[1024];
        int len;
        while ((len = rafRead.read(buf)) != -1) {
            rafWrite.write(buf, 0, len);
        }
        rafRead.close();
        rafWrite.close();
        long end = System.currentTimeMillis();
        System.out.println("traditionalCopy 用时为:" + (end - start)+"ms");
    }

}
